package ext.tianma.MaterialClassification;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wt.csm.navigation.ClassificationNode;
import wt.csm.navigation.litenavigation.ClassificationNodeDefaultView;
import wt.csm.navigation.service.ClassificationObjectsFactory;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.httpgw.URLFactory;
import wt.inf.container.WTContainer;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.WTPart;
import wt.pds.StatementSpec;
import wt.query.ConstantExpression;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.TableColumn;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.VersionReference;
import wt.vc.config.LatestConfigSpec;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.service.FinishedGoodService;
import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.QueryUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.finishedProduct.util.CSMUtil;
import ext.tianma.part.finishedProduct.util.TypesUtil;
import ext.tianma.part.finishedProduct.vo.AttrRuleVo;
import ext.tianma.part.finishedProduct.vo.ClassAttrRuleVo;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.util.ReadExcelUtil;

public class ReadClassification implements RemoteAccess {
	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/AVLPartClassifiaction.xlsx";
	public static String ATTRSORDER_PATH = "/codebase/ext/tianma/MaterialClassification/config/attrsOrder.properties";
	public static String softtype_finishgood = "cn.tianma.AVLMaterial";// APL类型
	private static final String CLASSNAME = ReadClassification.class.getName();
	private static Locale LOCALE = Locale.CHINA;

	public static void getName() throws WTException, RemoteException {
		QuerySpec qs = new QuerySpec(ClassificationNode.class);
		qs.setAdvancedQueryEnabled(true);
		int classNodeIndex = qs.appendClassList(ClassificationNode.class, true);
		String classNodeAliase = qs.getFromClause().getAliasAt(classNodeIndex);
		TableColumn ida3b6Col = new TableColumn(classNodeAliase, "ida3b6");
		qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL, new ConstantExpression("0")),
				new int[] { classNodeIndex });
		QueryResult queryResult = PersistenceHelper.manager.find(qs);
		while (queryResult.hasMoreElements()) {
			System.out.println("=====>>>>>>>>>");
			Persistable[] object = (Persistable[]) queryResult.nextElement();
			System.out.println("size===:" + object.length);
			ReferenceFactory rf = new ReferenceFactory();
			String objectOid = rf.getReferenceString(object[0]);// 通过对象获取oid
			System.out.println("objectOid===:" + objectOid);
			objectOid = rf.getReferenceString(object[1]);// 通过对象获取oid
			System.out.println("objectOid===:" + objectOid);
			if (object[0] instanceof ClassificationNode) {
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
				ClassificationNode node = (ClassificationNode) object[0];
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + node.getName());
			}

			if (object[1] instanceof ClassificationNode) {
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
				ClassificationNode node = (ClassificationNode) object[1];
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + node.getName());
			}
		}

	}

	/***
	 * 获取一级分类接口
	 * 
	 * @param classificationPath
	 * @return
	 * @throws Exception
	 */
	public static String getClassificationNode() throws Exception {

		List<String> ClassificationNodeList = new ArrayList<String>();
		JSONObject ob = new JSONObject();
		// 遍历excel
		System.out.println("===>>start==>>获取一级分类===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		JSONArray array = new JSONArray();
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH);
			is = new FileInputStream(STATUTE_PATH);

			System.out.println("=====>>>" + STATUTE_PATH);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell2;

			// 第一行为表头，从第二行开始遍历
			for (int i = 2, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					cell2 = row.getCell(0);
					ClassificationNodeList.add(cell2.toString());
				}
			}
			HashSet h = new HashSet(ClassificationNodeList);
			ClassificationNodeList.clear();
			ClassificationNodeList.addAll(h);
			System.out.println("ClassificationNodeList====>>"+ClassificationNodeList);
			if (ClassificationNodeList.size() > 0) {
				ob.put("status", "success");
				ob.put("message", "查询成功!");
				ob.put("data", ClassificationNodeList);
			} else {
				ob.put("status", "false");
				ob.put("message", "未查到！");
				ob.put("data", ClassificationNodeList);
			}
			ob.put("data", array);
			System.out.println("ob=====>>"+ob.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(is);
		}

		// QuerySpec qs = new QuerySpec(ClassificationNode.class);
		// qs.setAdvancedQueryEnabled(true);
		// int classNodeIndex = qs.appendClassList(ClassificationNode.class, true);
		// String classNodeAliase = qs.getFromClause().getAliasAt(classNodeIndex);
		// TableColumn ida3b6Col = new TableColumn(classNodeAliase, "ida3b6");
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("0")),new int[] { classNodeIndex });
		// QueryResult queryResult = PersistenceHelper.manager.find(qs);
		// while(queryResult.hasMoreElements()){
		// System.out.println("=====>>>>>>>>>");
		// Persistable[] object = (Persistable[]) queryResult.nextElement();
		// System.out.println("size===:"+object.length);
		// ReferenceFactory rf = new ReferenceFactory();
		// String objectOid = rf.getReferenceString(object[0]);// 通过对象获取oid
		// System.out.println("objectOid===:"+objectOid);
		// objectOid = rf.getReferenceString(object[1]);// 通过对象获取oid
		// System.out.println("objectOid===:"+objectOid);
		// if(object[0] instanceof ClassificationNode){
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
		// ClassificationNode node = (ClassificationNode) object[0];
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+node.getName());
		// }
		//
		// if(object[1] instanceof ClassificationNode){
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
		// ClassificationNode node = (ClassificationNode) object[1];
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+node.getName());
		// if(!ClassificationNodeList.contains(node.getName())) {//去重复
		//
		// ClassificationNodeList.add(node.getName());
		// }
		// }
		// if(ClassificationNodeList.size()>0) {
		// ob.put("status", "success");
		// ob.put("message", "查询成功!");
		// ob.put("data", ClassificationNodeList);
		// }else {
		// ob.put("status", "false");
		// ob.put("message", "未查到！");
		// ob.put("data", ClassificationNodeList);
		// }
		// }

		System.out.println("ClassificationNodeList===>>" + ClassificationNodeList);
		return ob.toString();
	}

	public static ClassificationNode getClassificationNodeByName(String classificationPath) throws Exception {
		QuerySpec spec = new QuerySpec(ClassificationNode.class);
		SearchCondition condition = new SearchCondition(ClassificationNode.class, ClassificationNode.COUNTERPART_ID,
				SearchCondition.EQUAL, classificationPath);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager.find((StatementSpec) spec);
		System.out.println("1111111>>>" + spec);
		while (result.hasMoreElements()) {
			return (ClassificationNode) result.nextElement();
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		// String type = args[0];
		// String states = args[1];
		if (!RemoteMethodServer.ServerFlag) {
			String method = "getClassificationNode";

			try {
				System.out.println("Debug   RemoteMethodServer...");
				RemoteMethodServer server = RemoteMethodServer.getDefault();
				server.setUserName("wcadmin");
				server.setPassword("tmadmin");
				System.out.println("...");
				RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, null, null);
				System.out.println("Debug  end RemoteMethodServer...");
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		} else {
			System.out.println("Debug   importBoms...");
			System.out.println("1111======>>>");
			getClassificationNode();
			System.out.println("Debug   end importBoms...");
		}

	}

	/***
	 * 获取子分类
	 * 
	 * ClassificationNode表中 当ida3b6=0时获取父分类 查询到父分类去ida2a2作为ida3b6的值查询该父下面的子
	 * 
	 * @return
	 * @throws WTException
	 * @throws JSONException
	 */
	public static String getClassificationChildNode(String classificationName) throws WTException, JSONException {

		System.out.println("==获取二级分类====");
		JSONObject ob = new JSONObject();
		// 读取Excel
		List<String> classifictionStr = new ArrayList<String>();
		classifictionStr = ReadExcelUtil.getCascade(STATUTE_PATH, classificationName);
		// //String classificationName="二级物料";

		// //List<String> ClassificationChildNodeList = new ArrayList<String>();
		// List<String> lists = new ArrayList<String>();
		// //String classifactionName1 = "";
		// //String classifactionName2 = "";
		// List<String> ClassificationNodeList = new ArrayList<String>();
		// QuerySpec qs = new QuerySpec();
		// qs.setAdvancedQueryEnabled(true);
		// int classNodeIndex = qs.appendClassList(ClassificationNode.class, true);
		// String classNodeAliase = qs.getFromClause().getAliasAt(classNodeIndex);
		// TableColumn ida3b6Col = new TableColumn(classNodeAliase, "ida3b6");
		// if(classificationName.equals("BLU类")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("382560795")),new int[] { classNodeIndex });
		// }else if(classificationName.equals("FPC空板")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("384733428")),new int[] { classNodeIndex });
		// }else if(classificationName.equals("电子元器件类")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("384733429")),new int[] { classNodeIndex });
		// }else if(classificationName.equals("辅材类")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("391046153")),new int[] { classNodeIndex });
		// }else if(classificationName.equals("LENS类")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("385473130")),new int[] { classNodeIndex });
		// }else if(classificationName.equals("TP类")) {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("391049894")),new int[] { classNodeIndex });
		// }else {
		// qs.appendWhere(new SearchCondition(ida3b6Col, SearchCondition.EQUAL,
		// new ConstantExpression("1")),new int[] { classNodeIndex });
		// }
		// System.out.println("qs=====>>>"+qs);
		// QueryResult queryResult = PersistenceHelper.manager.find(qs);
		// while(queryResult.hasMoreElements()){
		// Persistable[] object = (Persistable[]) queryResult.nextElement();
		// if(object[0] instanceof ClassificationNode){
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
		// ClassificationNode node = (ClassificationNode) object[0];
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+node.getName());
		// ClassificationNodeList.add(node.getName());
		// HashSet h = new HashSet(ClassificationNodeList);
		// lists.clear();
		// lists.addAll(h);
		// }
		////
		//// if(object[1] instanceof ClassificationNode){
		//// System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
		//// ClassificationNode node = (ClassificationNode) object[1];
		//// System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+node.getName());
		////
		//// }
		// }
		if (classifictionStr.size() > 0) {
			ob.put("status", "success");
			ob.put("message", "查询成功!");
			ob.put("data", classifictionStr);
		} else {
			ob.put("status", "false");
			ob.put("message", "未查到！");
			ob.put("data", classifictionStr);
		}
		System.out.println("ClassificationNodeList===>>" + classifictionStr);
		return ob.toString();
	}

	/**
	 * 根据节点名称获取分类属性
	 * @param classifictionName
	 * @return {researchName: "Waterabsorption", showName: "吸水率(%)",options:[{name:'1',value:'1'},{name"'2',value:'2'}],type:"combox"},
               {researchName: "Waterabsorption", showName: "吸水率(%)",options:[],type:"text"}
	 * @throws WTException
	 * @throws RemoteException
	 * @throws JSONException
	 */
	public static String getClassifictionIba(String classifictionName)
			throws WTException, RemoteException, JSONException {
		System.out.println("=====>>>start===>>");
		String classifiIda2a2 = ReadExcelUtil.getIda2a2(STATUTE_PATH, classifictionName);
		System.out.println("classifiIda2a2====>>" + classifiIda2a2);
		String classNodeOid = "OR:"+ClassificationNode.class.getName()+":"+classifiIda2a2;
		ClassificationNode classNode = (ClassificationNode) CoreUtil.getWTObjectByOid(classNodeOid);
		JSONObject retJson = new JSONObject();
		JSONArray attrArray = new JSONArray();
		if (classNode != null) {
			//获取节点下所有属性<内部名称，显示名称>
		    Map<String, String> classNodeAllIBAs = CSMUtil.getClassNodeAllIBAs(classNode);
		    ClassificationNodeDefaultView cndv = ClassificationObjectsFactory.newClassificationNodeDefaultView(classNode);
	    	String fullPath = CSMUtil.getClassificationFullPath(cndv);
	    	PropertiesUtil ut = new PropertiesUtil(ATTRSORDER_PATH);
	    	String orderAttrs = ut.getValueByKey(fullPath);
	    	System.out.println("orderAttrs======>>"+orderAttrs);
	    	String[] orderAttrArray = orderAttrs.split(";");
			
			for(int i = 0;i<orderAttrArray.length;i++){
				JSONObject attrObj = new JSONObject();
				JSONArray comboxValue = new JSONArray();
				String attrInternalName = orderAttrArray[i];
				if(StringUtils.isEmpty(attrInternalName)){
					continue;
				}
				JSONObject jsonObjTemp1 = new JSONObject();
				jsonObjTemp1.putOpt("name", "");
				jsonObjTemp1.putOpt("value", "");
				System.out.println("attrInternalName======>>"+attrInternalName);
				if(classNodeAllIBAs.containsKey(attrInternalName)){
					//分类属性
					ClassAttrRuleVo classAttrRuleVo = CSMUtil.getClassAttrInfo(classNode, attrInternalName);
					attrObj.put("researchName", attrInternalName);
					attrObj.put("showName", classAttrRuleVo.getDisplayName());
					if(null != classAttrRuleVo.getLegalValueList() && classAttrRuleVo.getLegalValueList().size()>0){
						comboxValue.put(jsonObjTemp1);
						for(String strTemp : classAttrRuleVo.getLegalValueList()){
							JSONObject jsonObjTemp = new JSONObject();
							jsonObjTemp.putOpt("name", strTemp);
							jsonObjTemp.putOpt("value", strTemp);
							comboxValue.put(jsonObjTemp);
						}
					}else if(null != classAttrRuleVo.getIntArray() && classAttrRuleVo.getIntArray().length>0){
						comboxValue.put(jsonObjTemp1);
						for(Integer intTemp : classAttrRuleVo.getIntArray()){
							JSONObject jsonObjTemp = new JSONObject();
							jsonObjTemp.putOpt("name", intTemp);
							jsonObjTemp.putOpt("value", intTemp);
							comboxValue.put(jsonObjTemp);
						}
					}
					attrObj.put("options", comboxValue);
				}else{
					//PDM属性
					AttrRuleVo attrRuleVo = TypesUtil.queryTypeDef(softtype_finishgood, attrInternalName);
					String ibaName = TypesUtil.getAttrIBAInternalName(softtype_finishgood, attrInternalName);
					attrObj.put("researchName", ibaName);
					attrObj.put("showName", attrRuleVo.getDisplayName());
					if(null != attrRuleVo.getLegalValueList() && attrRuleVo.getLegalValueList().size()>0){
						comboxValue.put(jsonObjTemp1);
						for(String strTemp : attrRuleVo.getLegalValueList()){
							JSONObject jsonObjTemp = new JSONObject();
							jsonObjTemp.putOpt("name", strTemp);
							jsonObjTemp.putOpt("value", strTemp);
							comboxValue.put(jsonObjTemp);
						}
					}else if(null != attrRuleVo.getEnumMap() && attrRuleVo.getEnumMap().size()>0){
						comboxValue.put(jsonObjTemp1);
						for(Entry<String, String> enty :attrRuleVo.getEnumMap().entrySet()){
							JSONObject jsonObjTemp = new JSONObject();
							jsonObjTemp.putOpt("name", enty.getValue());
							jsonObjTemp.putOpt("value", enty.getKey());
							comboxValue.put(jsonObjTemp);
						}
					}
					attrObj.put("options", comboxValue);
				}
				if(comboxValue.length() > 0){
					attrObj.put("type", "combox");
				}else{
					attrObj.put("type", "text");
				}
				
				attrArray.put(attrObj);
			}
		}
		retJson.put("data", attrArray);
		System.out.println("======>>"+retJson.toString());
		return retJson.toString();
	}

	public static String searchWTPart(Map<String, String> map) throws Exception {
		String avlPartNumber = "";
		System.out.println("===getWTPart start:" + map.toString());
		List<WTPart> listPart = new ArrayList<WTPart>();
		String name = "";
		String number = "";
		String state = "";
		JSONObject ob = new JSONObject();
		JSONArray array = new JSONArray();
		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.setAdvancedQueryEnabled(true);
		// IBA 属性过滤
		String condition = SearchCondition.EQUAL;
//		String condition = SearchCondition.LIKE;
		System.out.println("SearchCondition.LIKE==>>"+SearchCondition.LIKE);
		System.out.println("condition==>>"+condition);
		if (map.size() > 0) {
			Iterator<String> iter = map.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				String value = map.get(key).toString();
				if (map.get(key) != null) {
					value = map.get(key).toString();

					// 根据显示名称是否查找的到判断属性key的类型
					String displayname = FinishedGoodService.queryDisplayName(key, "string");
					String floatdisplayname = FinishedGoodService.queryDisplayName(key, "float");

					if (!StringUtil.isNullOrEmpty(displayname)) {
						// 字符串类型 StringDefination
						System.out
								.println("=================getWTPartByATT String displayname==========" + displayname);
						qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, key, value, condition),
								new int[] { 0 });
					} else if (!StringUtil.isNullOrEmpty(floatdisplayname)) {
						// float类型 FloatDefination
						System.out.println("=================getWTPartByATT float displayname==========" + displayname);
						qs.appendWhere(QueryUtil.getIBASearchConditionByFloat(WTPart.class, key, value, condition),
								new int[] { 0 });

					}
					if (iter.hasNext()) {
						qs.appendAnd();
					}
				}
			}
			// 最新版本
			System.out.println("=================getWTPartByATT qs==========" + qs.toString());
			QueryResult qr = PersistenceHelper.manager.find(qs);
			System.out.println("=================getWTPartByATT qr==========" + qr);

			qr = new LatestConfigSpec().process(qr);

			while (qr.hasMoreElements()) {
				// Object[] obj = (Object[]) qr.nextElement();
				WTPart part = (WTPart) qr.nextElement();
				System.out.println("..............result:" + part.getNumber());
				listPart.add(part);

			}
			if (listPart.size() > 0) {
				for (int i = 0; i < listPart.size(); i++) {
					WTPart part = listPart.get(i);
					number = part.getNumber();// 编号
					name = part.getName();// 名称
					state = part.getState().getState().getDisplay(LOCALE);// 状态
					ob.put("status", "success");
					ob.put("message", "查询成功!");
					JSONObject obInner = new JSONObject();
					obInner.put("partName", name);
					obInner.put("partNumber", number);
					obInner.put("partState", state);
					array.put(obInner);
				}
				ob.put("data", array);
				avlPartNumber = number;
			} else {
				ob.put("status", "false");
				ob.put("message", "未查到！");
				ob.put("data", listPart);
				avlPartNumber = "";
			}
		} else {
			ob.put("status", "false");
			ob.put("message", "请必须输入一个查询条件");
			ob.put("data", listPart);
			avlPartNumber = "";
		}
		return avlPartNumber;
	}

	public static String getWTPart(Map<String, String> map,String nodeName) throws Exception {
		System.out.println("===getWTPart start:" + map.toString());
		List<WTPart> listPart = new ArrayList<WTPart>();
		String name = "";
		String number = "";
		String state = "";
		JSONObject ob = new JSONObject();
		JSONArray array = new JSONArray();
		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.setAdvancedQueryEnabled(true);
		QueryUtil.appendTypeCondition(qs, softtype_finishgood);
		// IBA 属性过滤
//		String condition = SearchCondition.EQUAL;
		String condition = SearchCondition.LIKE;
		System.out.println("SearchCondition.LIKE===>>"+SearchCondition.LIKE);
		qs.appendAnd();
		Iterator<String> iter = map.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			String value = map.get(key).toString();
			if (map.get(key) != null) {
				value = map.get(key).toString();

				// 根据显示名称是否查找的到判断属性key的类型
				String displayname = FinishedGoodService.queryDisplayName(key, "string");
				String floatdisplayname = FinishedGoodService.queryDisplayName(key, "float");

				if (!StringUtil.isNullOrEmpty(displayname)) {
					// 字符串类型 StringDefination
					System.out.println("=================getWTPartByATT String displayname==========" + displayname);
					qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, key, "%"+value+"%", condition),
							new int[] { 0 });
				} else if (!StringUtil.isNullOrEmpty(floatdisplayname)) {
					// float类型 FloatDefination
					System.out.println("=================getWTPartByATT float displayname==========" + displayname);
					qs.appendWhere(QueryUtil.getIBASearchConditionByFloat(WTPart.class, key, "%"+value+"%", condition),
							new int[] { 0 });

				}
				if (iter.hasNext()) {
					qs.appendAnd();
				}
			}
		}
		// 最新版本
		System.out.println("=================getWTPartByATT qs==========" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		System.out.println("=================getWTPartByATT qr==========" + qr);

		qr = new LatestConfigSpec().process(qr);

		while (qr.hasMoreElements()) {
			// Object[] obj = (Object[]) qr.nextElement();
			WTPart part = (WTPart) qr.nextElement();
			System.out.println("..............result:" + part.getNumber());
			String cName = ClassificationUtil.getClassificationNode(part).getName();
			System.out.println("SLC ==分类名称==>"+nodeName+" | "+cName);
			if(nodeName.equals(cName)){
				listPart.add(part);
			}
		}
		if (listPart.size() > 0) {
			for (int i = 0; i < listPart.size(); i++) {
				WTPart part = listPart.get(i);
				number = part.getNumber();// 编号
				String ibaValue = (String) IBAUtil.getIBAValue(part, "MaterialType");
				name = part.getName();// 名称
				state = part.getState().getState().getDisplay(LOCALE);// 状态
				ob.put("status", "success");
				ob.put("message", "查询成功!");
				JSONObject obInner = new JSONObject();
				obInner.put("partName", name);
				obInner.put("partNumber", number);
				obInner.put("MaterialType", ibaValue);
				obInner.put("partState", state);
				array.put(obInner);
			}
			ob.put("data", array);
		} else {
			ob.put("status", "false");
			ob.put("message", "未查到！");
			ob.put("data", listPart);
		}
		return ob.toString();
	}

	/***
	 * 根据分类属性值查询物料
	 * 
	 * @param ibaValue
	 * @return
	 * @throws QueryException
	 */
	public static List<String> getWTPartByClassification(String ibaValue) throws QueryException {
		List<String> partList = new ArrayList<String>();
		WTPart part = null;
		QuerySpec spec = new QuerySpec(ClassificationNode.class);
		return partList;

	}

	/***
	 * 根据物料获取物料详细信息页面URL
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	public static String partGenerateInfoPageURL(WTPart part) throws WTException {
		String url = "";
		ReferenceFactory referenceFactory = new ReferenceFactory();
		URLFactory urlfactory = new URLFactory();
		String baseHref = urlfactory.getBaseHREF();
		if (part != null && part.getNumber() != null) {
			WTContainer container = part.getContainer();
			String ufid = referenceFactory.getReferenceString(VersionReference.newVersionReference((Iterated) part));
			String containerOid = "";
			if (container != null) {
				containerOid = referenceFactory.getReferenceString(container);
			}
			if ("".equals(containerOid)) {
				url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
			} else {
				url = baseHref + "app/#ptc1/tcomp/infoPage?ContainerOid=" + containerOid + "&oid=" + ufid + "&u8=1";
			}
		}
		return url;
	}

	/**
	 * 根据分类获取分类属性
	 * 
	 * @param name
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static List<String> getClassifictionIbaValue(String name) throws WTException, RemoteException {
		List<String> ibaList = new ArrayList<String>();
		ClassificationNode node = null;
		QuerySpec spec = new QuerySpec(ClassificationNode.class);
		SearchCondition condition = new SearchCondition(ClassificationNode.class, ClassificationNode.NAME,
				SearchCondition.EQUAL, name);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager.find((StatementSpec) spec);
		while (result.hasMoreElements())
			node = (ClassificationNode) result.nextElement();
		System.out.println("node name:" + node.getName());
		System.out.println("parent node name:" + node.getParent().getName());
		Hashtable values = IBAUtil.getIBAValues(node);
		Iterator ibaiter = values.keySet().iterator();
		while (ibaiter.hasNext()) {
			String key = ibaiter.next().toString();
			if (values.get(key) != null && values.get(key) instanceof String) {
				// String displayname = FinishedGoodService.queryDisplayName(key, "string");
				String value = (String) values.get(key);
				System.out.println("node key:" + key + "--value:" + value + "--显示名称：");
			} else if (values.get(key) != null) {
				String value = values.get(key).toString();
				System.out.println("node2 key:" + key + "--value:" + value + "<br/>");
			}
			ibaList.add(key);
		}
		return ibaList;
		// ClassificationNode node = ClassificationUtil.getClassificationNode(part);
		// out.print("node name:"+node.getName()+"<br/>");
		// out.print("parent node name:"+node.getParent().getName()+"<br/>");
		// Hashtable values = IBAUtil.getIBAValues(node);
		// Iterator ibaiter = values.keySet().iterator();
		// while (ibaiter.hasNext()) {
		// String key = ibaiter.next().toString();
		// if(values.get(key) !=null && values.get(key) instanceof String){
		// String displayname = FinishedGoodService.queryDisplayName(key, "string");
		// String value = (String)values.get(key);
		// out.print("node key:"+key+"--value:"+value+"--显示名称："+displayname+"<br/>");
		// }else if(values.get(key) !=null ){
		// String value = values.get(key).toString();
		// out.print("node2 key:"+key+"--value:"+value+"<br/>");
		// }
		//

	}

	/**
	 * 根据IBA属性获取成品信息数据
	 * 
	 * @param lang
	 * @return
	 * 
	 * 		<1,2,3> <2,4,5,6>
	 */
	public static void getFinishGoodInfo(Map<String, String> keylist) throws WTException {
		Map<String, String> mapList = new HashMap<String, String>();
		try {
			QuerySpec qs = new QuerySpec(WTPart.class);
			qs.setAdvancedQueryEnabled(true);
			// IBA 属性过滤
			String condition = SearchCondition.EQUAL;
			for (Map.Entry<String, String> entry : keylist.entrySet()) {
				System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
				String key = entry.getKey();
				String value = entry.getValue();
				if (keylist.get(key) != null) {
					value = keylist.get(key).toString();
					qs.appendAnd();
					// 其他为字符串类型
					qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, key, value, condition),
							new int[] { 0 });
				}
			}
		} catch (Exception e) {
			// e.printStackTrace();
			System.out.println("====exception:" + e.getMessage());
		}
	}

	/***
	 * 根据物料编号查询分类属性值
	 * 
	 * @param partNumber
	 */
	public static Map<String, String> getClassifictionIbaValueByPartNumber(String partNumber) {
		Map<String, String> mapIbaValue = new HashMap<String, String>();
		WTPart part = null;
		try {
			QuerySpec qs = new QuerySpec(WTPart.class);
			qs.appendAnd();
			SearchCondition condition = new SearchCondition(ClassificationNode.class, WTPart.NUMBER,
					SearchCondition.EQUAL, partNumber);
			QueryResult qr = PersistenceServerHelper.manager.query(qs);
			while (qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
				ext.tianma.bom.util.IBAUtil iba = new ext.tianma.bom.util.IBAUtil(part);
				// 根据物料获取物料分类再获取分类属性内部名称

				// 根据物编号获取物料分类

				// 根据分类名称获取分类属性内部名称

				// 根据内部分类属性名称获取分类属性值
				System.out.println("----------Part2:" + iba.getIBAValue(""));
			}
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return mapIbaValue;
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
